﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DrugStore.Models;

namespace DrugStore
{
    public class MyAuthorize : AuthorizeAttribute
    {
        public string LoginPage { get; set; }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            //if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            //{
            //    String returnUrl = filterContext.RequestContext.HttpContext.Request.Url.PathAndQuery;
            //    returnUrl = HttpUtility.UrlEncode(returnUrl);
            //    filterContext.HttpContext.Response.Redirect(LoginPage+"?returnUrl="+returnUrl);
            //}
            base.OnAuthorization(filterContext);
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //filterContext.HttpContext.Response.StatusCode = 404;
            //throw new HttpException(404, "Not Found");
            if (!String.IsNullOrEmpty(LoginPage))
            {
                String returnUrl = filterContext.RequestContext.HttpContext.Request.Url.PathAndQuery;
                returnUrl = HttpUtility.UrlEncode(returnUrl);
                filterContext.HttpContext.Response.Redirect(LoginPage + "?returnUrl=" + returnUrl);
            }
            base.HandleUnauthorizedRequest(filterContext);
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!String.IsNullOrEmpty(httpContext.User.Identity.Name))
            {
                DateTime now = DateTime.Now;
                DrugStoreEntities entities = new DrugStoreEntities();
                Admin account = entities.Admins.FirstOrDefault(a => a.Name == httpContext.User.Identity.Name);

                if (account == null)
                {
                    httpContext.Response.Redirect("/Account/LogOff");
                    return false;
                }                            
            }
            return base.AuthorizeCore(httpContext);
        }

        protected override HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext)
        {
            return base.OnCacheAuthorization(httpContext);
        }
    }
}
